#include "../gaussj.h"

#include <string>
#include <fstream>
#include <iomanip>
using namespace std;

int main(void) {
  int j, k, l, m, n;
  string dummy;
  ifstream fp("mt.txt");

  if (fp.fail()) {
    cerr << "Data file not found";
    exit(200);
  }

  cout << fixed << setprecision(6);
  getline(fp, dummy);
  while (!fp.eof()) {
    getline(fp, dummy);
    fp >> m >> n;
    fp.get();
    getline(fp, dummy);
    MatDoub a(m, m), u(m, m), b(m, n), t(m, n);
    for (k = 0; k < m; k++) {
      for (l = 0; l < m; l++) {
        fp >> a[k][l];
//        cout << a[k][l] << " ";
      }
      // cout << endl;
    }
    fp.get();
    getline(fp, dummy);
    for (l = 0; l < n; l++)
      for (k = 0; k < m; k++)
        fp >> b[k][l];
    fp.get();
    getline(fp, dummy);

    a.print();
    b.print();
    
    MatDoub ai = a;
    MatDoub x = b;

    // invert matrix.
    gaussj(ai, x);
    cout << endl << "Inverse of matrix a : " << endl;
    for (k = 0; k < m; k++) {
      for (l = 0; l < m; l++)
        cout << setw(12) << ai[k][l];
      cout << endl;
    }

    // check inverse
    cout << endl << " a times a-inverse: " << endl;
    for (k = 0; k < m; k++) {
      for (l = 0; l < m; l++) {
        u[k][l] = 0.0;
        for (j = 0; j < m; j++)
          u[k][l] += (a[k][j] * ai[j][l]);
      }
      for (l = 0; l < m; l++)
        cout << setw(12) << u[k][l];
      cout << endl;
    }

    // check vector solutions.
    cout << endl << "Checking the following for equality: " << endl;
    cout << setw(20) << "Orginal" << setw(15) << "Matrix*sol'n" << endl;

    for (l = 0; l < n; l++) {
      cout << "vector " << l << ": " << endl;
      for (k = 0; k < m; k++) {
        t[k][l] = 0.0;
        for (j = 0; j < m; j++)
          t[k][l] += (a[k][j] * x[j][l]);
        cout << setw(18) << b[k][l];
        cout << setw(18) << t[k][l] << endl;
      }
    }
    cout << "************************************" << endl;
    cout << "press Return for next problem: " << endl;
    cin.get();
  }
  fp.close();
  return 0;
}
    
